package com.xintonghua.bussiness.ui.user;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;

import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.xintonghua.base.utils.MyTimeUtils;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.base.BaseActivity;
import com.xintonghua.bussiness.ui.fragment.QrCodeActiivity;
import com.xintonghua.bussiness.util.MyState;
import com.xintonghua.bussiness.util.MyUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class QRCodeActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    @BindView(R.id.fl_my_container)
    FrameLayout flMyContainer;
    public static final int REQUEST_IMAGE = 112;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr_codes);
        ButterKnife.bind(this);
        initUI();
    }


    @Override
    public void initUI() {
        initPermission();
        /**
         * 执行扫面Fragment的初始化操作
         */
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);

        captureFragment.setAnalyzeCallback(analyzeCallback);
        /**
         * 替换我们的扫描控件
         */
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            if (TextUtils.isEmpty(result)) {
                return;
            }
            List<String> list = MyUtils.getListStringSplitValue(result);
            if (list.size() != 4) {
                return;
            }
            if (!list.get(2).equals(MyTimeUtils.getYYMMDDX(System.currentTimeMillis()))) {
                mToast("只能在今日内打开");
                return;
            }
            if (list.get(0).equals("hongyi") && list.get(1).equals("daka") && list.get(2).equals(MyTimeUtils.getYYMMDDX(System.currentTimeMillis()))) {
                httpCent.saveCheck(list.get(3), QRCodeActivity.this, MyState.requestOne);
            } else {

            }
        }

        @Override
        public void onAnalyzeFailed() {
            mToast("失败了");
        }
    };


    @Override
    public void dataBack(Object data, int order) {
        mToast("打卡成功！");
        finish();
        super.dataBack(data, order);
    }

    @Override
    public void errorBack(String error, int order) {
        mToast(error);
        finish();
        super.errorBack(error, order);
    }

    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;

        }
    }

    /**
     * 初始化权限事件
     */
    private void initPermission() {
        //检查权限
//        String[] permissions = CheckPermissionUtils.checkPermission(this);
//        if (permissions.length == 0) {
//            //权限都申请了
//            //是否登录
//        } else {
//            //申请权限
//            ActivityCompat.requestPermissions(this, permissions, 100);
//        }
    }

    /**
     * 请求CAMERA权限码
     */
    public static final int REQUEST_CAMERA_PERM = 101;


    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @AfterPermissionGranted(REQUEST_CAMERA_PERM)
    public void cameraTask(int viewId) {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_IMAGE);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要请求camera权限",
                    REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "当前App需要申请camera权限,需要打开设置页面么?")
                    .setTitle("权限申请")
                    .setPositiveButton("确认")
                    .setNegativeButton("取消", null /* click listener */)
                    .setRequestCode(REQUEST_CAMERA_PERM)
                    .build()
                    .show();
        }
    }


}
